package news.servlet;

import news.dao.NewsDao;
import news.pojo.News;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet("/news-detail")
public class DetailServlet extends HttpServlet {
    private NewsDao newsDao = new NewsDao();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");
        resp.setContentType("text/html;charset=utf-8");
        resp.setCharacterEncoding("utf-8");
        // 判断参数是否合法
        if (id == null || id.length() == 0) {
            resp.getWriter().println("参数非法");
            return;
        } else if (!id.matches("^\\d+$")) {
            resp.getWriter().println("新闻编号格式不正确");
            return;
        }
        // 查询数据库
        try {
            News news = newsDao.selectOne(Integer.valueOf(id));
            // 判断是否查询到对应的新闻
            if (news == null) {
                resp.getWriter().println("新闻不存在");
            }else{
                req.setAttribute("news",news);
                req.getRequestDispatcher("/WEB-INF/views/detail.jsp").forward(req, resp);
            }
        } catch (SQLException e) {
            e.printStackTrace();
            resp.getWriter().println("查询新闻异常:" + e.getMessage() + " <br>" + e.getSQLState());
        }

    }
}
